// 放入重复代码
import { mapActions, mapGetters } from 'vuex'
import { themeList, addCss, removeAllCss, getReadTimeByMinute } from './book'
import { getBookmark, saveLocation, getBookShelf, saveBookShelf } from './localStorage'
import { gotoBookDetail, appendAddToShelf, removeAddFromShelf, computeId } from './store'
import { shelf } from '../api/store'

export const storeShelfMixin = {
  computed: {
    ...mapGetters([
      'isInputMode',
      'isEditMode',
      'shelfList',
      'shelfSelected',
      'shelfTitleVisible',
      'offsetY',
      'shelfCategory',
      'currentType'
    ])
  },
  methods: {
    ...mapActions([
      'setIsInputMode',
      'setIsEditMode',
      'setShelfList',
      'setShelfSelected',
      'setShelfTitleVisible',
      'setOffsetY',
      'setShelfCategory',
      'setCurrentType'
    ]),
    // 显示书本详情页
    showBookDetail(book) {
      gotoBookDetail(this, book)
    },
    // 获取分组
    getCategoryList(title) {
      this.getShelfList().then(() => {
        const categoryList = this.shelfList.filter(book => book.type === 2 && book.title === title)[0]
        this.setShelfCategory(categoryList)
        // console.log(categoryList)
      })
    },
    // 获取书架书籍列表
    getShelfList() {
      //从localStorage中获取书架书籍数据
      let shelfList = getBookShelf()
      // console.log(shelfList)
      if (!shelfList) {
        // 从接口获取列表数据
        shelf().then(response => {
          // console.log(response)
          // 返回来的接口数据中的data属性存在，，data中的bookList属性存在
          if (response.status === 200 && response.data && response.data.bookList) {
            // 则添加 加号书籍 到书架中
            shelfList = appendAddToShelf(response.data.bookList)
            // 保存书籍到localStorage
            saveBookShelf(shelfList)
            return this.setShelfList(shelfList)
          }
        })
      } else {
        // 更新vuex 中的书架列表 返回一个promise对象
        return this.setShelfList(shelfList)
      }
    },
    // 书籍移出分组
    moveOutOfGroup(f) {
      this.setShelfList(this.shelfList.map(book => {
        // 分组内 并且有书籍 选中书籍在分组中删除
        if (book.type === 2 && book.itemList) {
          // console.log('aaa')
          book.itemList = book.itemList.filter(subBook => !subBook.selected)
        }
        return book
      })).then(() => {
        // let list = removeAddFromShelf(this.shelfList)
        // list = [].concat(list, ...this.shelfSelected)
        // list = appendAddToShelf(list)
        // list = computeId(list)
        // this.setShelfList(list).then(() => {
        //   this.simpleToast(this.$t('shelf.moveBookOutSuccess'))
        //   if (f) f()
        // 嵌套写法 将选中的书籍放入书架列表中
        const list = computeId(appendAddToShelf([].concat(
          removeAddFromShelf(this.shelfList), ...this.shelfSelected)))
        this.setShelfList(list).then(() => {
          this.simpleToast(this.$t('shelf.moveBookOutSuccess'))
          if (f) f()
        })
      })
    }
  }
}

export const storeHomeMixin = {
  computed: {
    ...mapGetters([
      'offsetY',
      'hotSearchOffsetY',
      'flapCardVisible'
    ])
  },
  methods: {
    ...mapActions([
      'setOffsetY',
      'setHotSearchOffsetY',
      'setFlapCardVisible'
    ]),
    // 显示书本详情页
    showBookDetail(book) {
      gotoBookDetail(this, book)
      this.setFlapCardVisible(false)
    }
  }
}

export const ebookMixin = {
  computed: {
    // 从vuex中的getter对象中获取属性
    ...mapGetters([
      'fileName',
      'menuVisible',
      'settingVisible',
      'defaultFontSize',
      'defaultFontFamily',
      'fontFamilyVisible',
      'defaultTheme',
      'bookAvailable',
      'progress',
      'section',
      'isPaginating',
      'currentBook',
      'navigation',
      'cover',
      'metadata',
      'paginate',
      'pagelist',
      'offsetY',
      'isBookmark'
    ]),
    // 主题列表 this是vue实例 这两个themeList表示的不同
    themeList() {
      return themeList(this)
    },
    // 获取章节名
    getSectionName() {
      // if (this.section) {
      //   // console.log(this.section)
      //   const sectionInfo = this.currentBook.section(this.section)
      //   // console.log(sectionInfo)
      //   if (sectionInfo && sectionInfo.href && this.currentBook && this.currentBook.navigation) {
      //     // 获取到目录中该章标题
      //     // console.log(this.currentBook.navigation.get(sectionInfo.href))
      //     // return this.currentBook.navigation.get(sectionInfo.href).label
      //     // get(sectionInfo.href) 只能获取一级目录 所以更改
      //   }
      // }
      // console.log(this.section)
      // 章节从0封面开始 章节数就是索引号，navigation中存的是目录信息而且是扁平化的
      return this.section ? this.navigation[this.section].label : ''
    }
  },
  methods: {
    ...mapActions([
      'setFileName',
      'setMenuVisible',
      'setSettingVisible',
      'setDefaultFontSize',
      'setDefaultFontFamily',
      'setFontFamilyVisible',
      'setDefaultTheme',
      'setBookAvailable',
      'setProgress',
      'setSection',
      'setIsPaginating',
      'setCurrentBook',
      'setNavigation',
      'setCover',
      'setMetadata',
      'setPaginate',
      'setPagelist',
      'setOffsetY',
      'setIsBookmark'
    ]),
    // 全局样式初始化
    initGlobalStyle() {
      // 清除之前添加的所有link样式标签
      removeAllCss()
      switch (this.defaultTheme) {
        case 'Default':
          // 在静态资源服务中获取
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_default.css`)
          break
        case 'Eye':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_eye.css`)
          break
        case 'Gold':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_gold.css`)
          break
        case 'Night':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_night.css`)
          break
        default:
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_default.css`)
          break
      }
    },
    // 刷新当前进度条位置
    refreshLocation() {
      const currentLocation = this.currentBook.rendition.currentLocation()
      // console.log(currentLocation)
      if (currentLocation && currentLocation.start) {
        // console.log(currentLocation.start)
        const startCfi = currentLocation.start.cfi
        const progress = this.currentBook.locations.percentageFromCfi(startCfi)
        // console.log(progress, currentLocation, startCfi)
        // 刷新进度数字显示
        this.setProgress(Math.floor(progress * 100))
        // 刷新章节标题显示 index就是章节数 就是目录标题索引号
        this.setSection(currentLocation.start.index)
        // 保存当前进度在localStorage
        saveLocation(this.fileName, startCfi)
        // 判断当前页是否为书签
        const bookmark = getBookmark(this.fileName)
        // console.log(bookmark)
        if (bookmark) {
          if (bookmark.some(item => item.cfi === startCfi)) {
            this.setIsBookmark(true)
            // console.log(this.isBookmark)
          } else {
            this.setIsBookmark(false)
          }
        } else {
          this.setIsBookmark(false)
        }
        // 分页的处理 书籍页数存在的话
        if (this.pagelist) {
          // 书籍总页数
          const totalPage = this.pagelist.length
          const currentPage = currentLocation.start.location
          if (currentPage && currentPage > 0) {
            // 显示分页信息 在页脚
            this.setPaginate(currentPage + ' / ' + totalPage)
          } else {
            this.setPaginate('')
          }
        } else {
          this.setPaginate('')
        }
      }
    },
    // 显示
    display(target, cb) {
      if (target) {
        this.currentBook.rendition.display(target).then(() => {
          this.refreshLocation()
          if (cb) cb()
        })
      } else {
        this.currentBook.rendition.display().then(() => {
          this.refreshLocation()
          if (cb) cb()
        })
      }
    },
    // 翻页隐藏标题栏和菜单栏
    hideTitleAndMenu() {
      // this.$store.dispatch('setMenuVisible', false)
      // 用了mapActions之后
      this.setMenuVisible(false)
      // 隐藏菜单栏之后 字号设置隐藏
      this.setSettingVisible(-1)
      // 隐藏字体设置栏
      this.setFontFamilyVisible(false)
    },
    // 阅读时间显示
    getReadTimeText() {
      return this.$t('book.haveRead').replace('$1', getReadTimeByMinute(this.fileName))
    }
  }
}
